package exttable.formgenerator;

import dbutils.DbUtils;
import exttable.dbclasses.DbTable;
import exttable.dbclasses.EGetID;
import utils.Localisation;

import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;

public class ComboBoxSelector {
    Object selectedItem;
    JComboBox jcb;
    JPanel panel;
    JButton nextButton;


    public ComboBoxSelector(String tableName, Object arrayItems[]) throws Exception {
        Connection conn = DbUtils.getDBConnectionGeneral();
        JFrame chooseFrame = new JFrame(TranslateFields.getTranslateOfColumnOrOfTable("table_traslation_list", "table_name", tableName, conn));
        panel = new JPanel();
        Border border = BorderFactory.createLineBorder(Color.BLACK, 2);
        panel.setBorder(border);
        jcb = new
                JComboBox(arrayItems);
        panel.add(jcb);
        nextButton = new JButton(Localisation.getMessage("form.continue"));
        nextButton.setName(tableName);

        panel.add(nextButton);
        chooseFrame.add(panel);
        chooseFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        chooseFrame.setVisible(true);
        chooseFrame.setSize(500, 200);
        init();
    }

    void init() {

        selectedItem = jcb.getSelectedItem();
        jcb.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (e.getSource() != null) {
                    JComboBox jcmbType = (JComboBox) e.getSource();
                    selectedItem = jcmbType.getSelectedItem();
                }
            }
        });
        nextButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Component comp = (Component) e.getSource();
                DbTable dbTable = new DbTable(DbUtils.GENERAL_DATABASE_NAME,comp.getName(), String.valueOf(EGetID.valueOf(comp.getName().toUpperCase()).
                        getID(selectedItem)));
                dbTable.setMapValuesFields(StaticMethods.getMapValuesFields(dbTable));
                new FormGenerator(comp.getName(), dbTable);
            }
        });

    }

}